package main;

import java.awt.*;

public class ControlCurve {

	protected Polygon pts;
	protected int selection = -1;
	static final int EPSILON = 36;

	public ControlCurve() {
		pts = new Polygon();
	}

	public void paint(Graphics g) {
		g.setColor(new Color(0, 155, 155));
		for (int i = 0; i < pts.npoints; i++) {
			g.fillOval(pts.xpoints[i] - 3, pts.ypoints[i] - 3, 6, 6);
			g.drawString(i + 1 + "", pts.xpoints[i] - 6, pts.ypoints[i] - 6);
		}
		g.setColor(new Color(0, 0, 155));
		for (int i = 0; i < pts.npoints - 1; i++) {
			g.drawLine(pts.xpoints[i], pts.ypoints[i], pts.xpoints[i + 1],
					pts.ypoints[i + 1]);
		}
	}

	public int selectPoint(int x, int y) {
		int mind = Integer.MAX_VALUE;
		selection = -1;
		for (int i = 0; i < pts.npoints; i++) {
			int d = sqr(pts.xpoints[i] - x) + sqr(pts.ypoints[i] - y);
			if (d < mind && d < EPSILON) {
				mind = d;
				selection = i;
			}
		}
		return selection;
	}

	static int sqr(int x) {
		return x * x;
	}

	public int addPoint(int x, int y) {
		pts.addPoint(x, y);
		return selection = pts.npoints - 1;
	}

	public void setPoint(int x, int y) {
		if (selection >= 0) {
			pts.xpoints[selection] = x;
			pts.ypoints[selection] = y;
		}
	}

	public void removePoint() {
		if (selection >= 0) {
			pts.npoints--;
			for (int i = selection; i < pts.npoints; i++) {
				pts.xpoints[i] = pts.xpoints[i + 1];
				pts.ypoints[i] = pts.ypoints[i + 1];
			}
		}
	}

	public String toString() {
		StringBuffer result = new StringBuffer();
		for (int i = 0; i < pts.npoints; i++) {
			result.append(" " + pts.xpoints[i] + " " + pts.ypoints[i]);
		}
		return result.toString();
	}
}
